package com.ruoyi.system.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiPredicate;

/**
 * 阈值操作符枚举
 */
@Getter
@AllArgsConstructor
@Slf4j
public enum ThresholdOperatorEnum {
    GREATER_THAN(">", (a, b) -> a > b),
    LESS_THAN("<", (a, b) -> a < b),
    EQUAL_TO("=", (a, b) -> a == b);

    public String getSymbol() {
        return symbol;
    }

    // 缓存枚举常量的 Map
    private static final Map<String, ThresholdOperatorEnum> OPERATOR_MAP;

    private final String symbol;

    private final BiPredicate<Double, Double> operation;

    // 静态初始化块，填充缓存
    static {
        OPERATOR_MAP = new HashMap<>();
        for (ThresholdOperatorEnum operator : ThresholdOperatorEnum.values()) {
            OPERATOR_MAP.put(operator.getSymbol(), operator);
        }
    }

    public static boolean apply(String symbol, Object a, Object b) {
        ThresholdOperatorEnum alarmOperateTypeEnum = getOperation(symbol);
        if (Objects.isNull(alarmOperateTypeEnum)) {
            return false;
        }

        return alarmOperateTypeEnum.test(a, b);
    }

    private boolean test(Object a, Object b) {
        if (Objects.isNull(a) || Objects.isNull(b)) {
            return false;
        }
        try {
            // 尝试将对象转换为 Double 类型
            Double doubleA = Double.parseDouble(a.toString());
            Double doubleB = Double.parseDouble(b.toString());
            return operation.test(doubleA, doubleB);
        } catch (Exception e) {
            log.error("ThresholdOperatorEnum.test error", e);
            return false;
        }
    }

    public static ThresholdOperatorEnum getOperation(String operType) {
        ThresholdOperatorEnum operator = OPERATOR_MAP.get(operType);
        if (operator == null) {
            log.warn("未知的 operator: " + operator);
        }
        return operator;
    }
}